package cn.com.libertymutual.core.xml;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.DocumentResult;
import org.springframework.oxm.Marshaller;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.context.DefaultMessageContext;
import org.springframework.ws.context.MessageContext;

import com.google.common.base.Strings;

public class XmlUtil {
	///private Logger log = LoggerFactory.getLogger(getClass());

	public XmlUtil() {
		
	}
	
	public Element selectSingleNode( Element element, String path ) {
		if( Strings.isNullOrEmpty(path) ) return null;
		
		String xpath = path.charAt(0) == '/' ? path.substring(1) : path;
		
		int offset = xpath.indexOf('/');
		String xpathTmp = null;
		if( offset >= 0 ) {
			xpathTmp = xpath.substring( offset + 1 );
			xpath = xpath.substring( 0, offset );
		}
		
		Element elt = element.element( xpath );
		
		if( elt != null && !Strings.isNullOrEmpty(xpathTmp) )
			elt = selectSingleNode(elt, xpathTmp);
		
		return elt;
	}
	
	/**
	 * org.jdom
	 * @param document
	 * @return
	 */
	public String getDocumentation( org.jdom2.Document document) {
			org.jdom2.Element rootEl = document.getRootElement();
			for (Iterator<?> iter = rootEl.getContent().iterator(); iter.hasNext();) {
				org.jdom2.Content content = (org.jdom2.Content) iter.next();
				if (content instanceof org.jdom2.Comment)
					return ((org.jdom2.Comment) content).getText();
				if (content instanceof org.jdom2.Text)
					continue;
				break;
			}

			org.jdom2.Element annoEl = rootEl.getChild("annotation", rootEl.getNamespace());
			if (annoEl != null) {
				return annoEl.getChildText("documentation", rootEl.getNamespace());
			}
			else {
				return rootEl.getChildText("documentation", rootEl.getNamespace());
			}
	}
	
	/**
	 * org.jdom
	 * @param jbiDoc
	 * @return
	 */
	public String getJbiDescription(org.jdom2.Document jbiDoc) {
		
			org.jdom2.Element rootEl = jbiDoc.getRootElement();
			List<?> list = rootEl.getChildren();
			if (list.size() > 0) {
				org.jdom2.Element idenEl, firstEl = (org.jdom2.Element)list.get(0);
				if ((idenEl = firstEl.getChild("identification", rootEl.getNamespace())) != null) {
					return idenEl.getChildText("description", rootEl.getNamespace());
				}
			}
	
		return null;
	}
	
	public String genWSXmlObjectToBuf( final Object requestPayload, Marshaller marshaller, WebServiceMessageFactory messageFactory ) throws Exception{
		MessageContext messageContext = new DefaultMessageContext( messageFactory ); 
		
		StringWriter   writer   =   new   StringWriter();   
        StreamResult   result   =   new   StreamResult(writer);   
		marshaller.marshal(requestPayload, messageContext.getRequest().getPayloadResult());
		TransformerFactory.newInstance().newTransformer().transform(messageContext.getRequest().getPayloadSource(), result);
		return writer.toString();
	}
	
	public Document genWSXmlObject( final Object requestPayload, Marshaller marshaller, WebServiceMessageFactory messageFactory ) throws Exception{
		MessageContext messageContext = new DefaultMessageContext( messageFactory );
		DocumentResult    result   =   new   DocumentResult( );	
		WebServiceMessage request = messageContext.getRequest();
		marshaller.marshal(requestPayload, request.getPayloadResult());
		TransformerFactory.newInstance().newTransformer().transform(request.getPayloadSource(), result);
		return result.getDocument();
	}

	public String selectSingleString( Document doc, String xpath ) {
		Node node = doc.selectSingleNode(xpath);
		
		return node != null ? node.getText() : "";
	}
	
	public Node selectSingleNode( Document doc, String xpath ) {
		return doc.selectSingleNode( xpath );
	}
}
